<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\services\LoginService;
use app\BaseController;
use app\common\exceptions\Exception;
use app\common\model\Rabc\AdminLoginLogs;
use think\facade\Session;
use think\Request;

class Logins extends BaseController
{
    public function index(Request $request)
    {
        if ($request->isPost()){
            $admin_name = $request->param('login_name', '');
            $password = $request->param('password', '');
            try {
                $admin = LoginService::login($admin_name, $password);
                // 登录日志
                AdminLoginLogs::getInstance()->record($admin);

                // 存入Session
                Session::set('login_admin', $admin);

                // 跳转主页
                return $this->successJson([], '登录成功');
            } catch (Exception $e) {
                // 登录日志
                AdminLoginLogs::getInstance()->record(0, 0, $e->getMessage());

                return $this->errorJson($e->getMessage());
            }
        }else{
            if ($admin = getLoginAdmin()){
                if ($admin->admin_id) return redirect('/admin/indexs/index');
            }
            return view(cnpscy_config('admin_template') . '/' . $request->controller(true) . '/' . $request->action());
        }
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function logout()
    {
        Session::delete('login_admin');
        return redirect('/admin/logins/index');
    }
}
